//
//  SendCodeController.m
//  QQplayground
//
//  Created by zhangxy on 2018/5/23.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "SendCodeController.h"
#import "BaseTabBarController.h"
#import <UMShare/UMShare.h>
#import "ZCTTMLEmojiLabel.h"
#import "ZTextField.h"
#import "BaseTabBarController.h"
#import "RegisterController.h"

@interface SendCodeController ()<ZCTTMLEmojiLabelDelegate,UIGestureRecognizerDelegate>{
    CGFloat startY;
    int time;
}

@property(nonatomic,strong) UIView *regView;
@property(nonatomic,strong) ZTextField *txtCode;
@property(nonatomic,strong) ZCTTMLEmojiLabel *labCode;
@property(nonatomic,strong) UIButton *preButton;
@property(nonatomic,strong) UIButton *nextButton;




@end

@implementation SendCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    self.view.userInteractionEnabled = YES;
    
    
    [self createTitleMenu];
    [self.menuTitleButton setTitle:@"输入验证码" forState:0];
    [self.titleMenu setBackgroundColor:UIColor.clearColor];
    
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateNormal];
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateHighlighted];
    
    [self createVCView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyboard:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    self.navigationController.navigationBar.hidden = NO;
}


// 隐藏键盘
-(void)hiddenKeyboard:(id)sender
{
    [_txtCode resignFirstResponder];
}


-(void)doThirdLogin:(UIButton *) sender{
    if(sender.tag == 12){
        [self backAction];
    }
    if(sender.tag == 11){
        DLog(@"获取验证码");
        
        NSDictionary *params = @{@"phone":_phone, @"phone_area_code":_phone_area_code, @"sms_code":_txtCode.text, @"ver":[ZZCoreTools getAppBuildVersion]};
        [NetworkUtil POST:API_CheckSmsCode parameters:params success:^(id responseObject, NSDictionary *dict) {
            RegisterController *vc = [[RegisterController alloc] init];
            vc.phone = convertToString(_phone);
            vc.phone_code = convertToString(_txtCode.text);
            vc.isRegister = YES;
            vc.phone_area_code = convertToString(_phone_area_code);
            [self openPushVC:vc];
            
        } failure:^(NSError *error, NSString *message) {
            if(convertToString(message).length>0){
                [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
            }
        }];
    }
}



-(void)createVCView{
    UIImage *backImage =[UIImage imageNamed:@"base_bg.jpg"];
    self.view.layer.contents=(id)backImage.CGImage;
    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
    self.view.layer.backgroundColor = UIColorFromRGB(0x67ACA6).CGColor;
    
    
    startY = 210;
    
    
//    UIButton *backBtn = [self createButton:@"login_close"];
//    [backBtn setFrame:CGRectMake(0, StatusBarHeight, 44, 44)];
//    [backBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
//    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 100, 124, 200, 30)];
    [iconView setImage:[UIImage imageNamed:@"qzone"]];
    [iconView setContentMode:UIViewContentModeScaleAspectFit];
    [iconView setBackgroundColor:UIColor.clearColor];
    
    
    
    
    _regView   = [[UIView alloc] initWithFrame:CGRectMake(0, startY, ScreenWidth, ScreenHeight-startY)];
    _regView.backgroundColor = UIColor.clearColor;
    
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(20, startY-40, ScreenWidth - 40, 30)];
    [lab setFont:ListDetailFont];
    [lab setTextColor:UIColorFromRGB(TextDarkColor)];
    if(validatePhone(_phone)){
        NSString *tempStr = [_phone substringToIndex:_phone.length - 4];
        
        NSString *txtPhone = [_phone stringByReplacingOccurrencesOfString:tempStr withString:@"********"];
        lab.text = txtPhone;
    }
    
    [self.view addSubview:_regView];
    
    
    [self createRegisterView];
    
//    [self.view addSubview:backBtn];
    [self.view addSubview:iconView];
}



-(void)createRegisterView{
    
    CGFloat y = 10;
    UIView *itemBgView = [[UIView alloc] initWithFrame:CGRectMake(20, y, ScreenWidth-40, 55)];
    itemBgView.layer.cornerRadius = 11.0f;
    itemBgView.layer.masksToBounds  = YES;
    [itemBgView setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    [_regView addSubview:itemBgView];
    
    _txtCode = [self createTextField:@"输入验证码" y:y];
    [_txtCode setTextAlignment:NSTextAlignmentCenter];
    [_txtCode setFrame:CGRectMake(0, 10, ScreenWidth - 40, 35)];
    [_txtCode setKeyboardType:UIKeyboardTypePhonePad];
    [_txtCode setFont:ListTitleFont];
    [itemBgView addSubview:_txtCode];
    
    y = y + 55 + 25;
    
    _labCode = [self createLinkLabel:y];
    [_labCode setTextAlignment:NSTextAlignmentCenter];
    [_regView addSubview:_labCode];
    [self addLinkMessage:_labCode text:[NSString stringWithFormat:@"没收到验证码？<a href=\"s\">%d秒</a> 以后可以重新发送",time]];
    
    y = y + 20 + 30;
    
    _nextButton = [self createButton:@""];
    [_nextButton setFrame:CGRectMake(ScreenWidth/2 - 121/2, y, 121, 57)];
    [_nextButton setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    _nextButton.layer.cornerRadius = 29.0f;
    _nextButton.layer.masksToBounds = YES;
    [_nextButton setTitle:@"下一步" forState:0];
    [_nextButton setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
    [_nextButton.titleLabel setFont:ListTitleFont];
    _nextButton.tag = 11;
    [_nextButton addTarget:self action:@selector(doThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    [_nextButton setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateDisabled];
    [_regView addSubview:_nextButton];
    
    y = y + 67 + 10;
    
    _preButton = [self createButton:@""];
    [_preButton setFrame:CGRectMake(ScreenWidth/2 - 121/2, y, 121, 57)];
    [_preButton setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    _preButton.layer.cornerRadius = 29.0f;
    _preButton.layer.masksToBounds = YES;
    [_preButton setTitle:@"上一步" forState:0];
    [_preButton setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
    [_preButton.titleLabel setFont:ListTitleFont];
    _preButton.tag = 12;
    [_preButton addTarget:self action:@selector(doThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    [_regView addSubview:_preButton];
    
    
    
    
    
    [self looperTimer];
}


-(void)looperTimer{
    time = 60;
    
    NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self addLinkMessage:self.labCode text:[NSString stringWithFormat:@"没收到验证码？<a href=\"s\">%d秒</a> 以后可以重新发送",time]];
        time = time - 1;
        if(time <= 0){
            
            self.nextButton.enabled = NO;
            [self.nextButton setBackgroundColor:UIColorFromRGB(BgListSectionColor)];
            
            [self addLinkMessage:self.labCode text:[NSString stringWithFormat:@"没收到验证码？<a href=\"resend\">重新发送</a>"]];
            
            [timer1 invalidate];
        }
    }];
    
}

- (void)imgCodeShow
{
    //发送网络请求，想服务器端验证图形验证码的正确性
    NSDictionary *params = [[NSDictionary alloc] initWithObjects:@[_phone,convertToString(_phone_area_code)] forKeys:@[@"phone",@"phone_area_code"]];
    DLog(@"params：%@",params);
    [NetworkUtil POST:API_SendSms parameters:params success:^(id responseObject, NSDictionary *dict) {
        [PopUtil showMessage:@"验证码已发送" positionType:PopPositionTypeMiddle];
        
        _nextButton.enabled = YES;
        [_nextButton setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
        
        [self looperTimer];
    } failure:^(NSError *error, NSString *message) {
        if(convertToString(message).length>0){
            [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
        }
    }];
}




-(UIButton *) createButton:(NSString *) imageName{
    UIButton *btn = ({
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setImage:[UIImage imageNamed:convertToString(imageName)] forState:0];
        backBtn;
    });
    return btn;
}

-(ZTextField *) createTextField:(NSString *) placeHolder y:(CGFloat )ty{
    ZTextField *btn = ({
        ZTextField *backBtn = [[ZTextField alloc] initWithImage:nil padding:5];
        [backBtn setFrame:CGRectMake(20, ty, ScreenWidth-40, 52)];
        [backBtn setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
        backBtn.layer.cornerRadius = 10.0f;
        backBtn.layer.masksToBounds = YES;
        [backBtn setFont:ListDetailFont];
        [backBtn setPlaceholder:placeHolder];
        
        backBtn;
    });
    return btn;
}

#pragma mark - gesture delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"ZCTTMLEmojiLabel"]) {
        return NO;
        
        //        if(![@"" isEqualToString:morelink ] && morelink!= nil && self.delegate && [self.delegate respondsToSelector:@selector(cellItemClick:type:obj:)]){
        //            [self.delegate cellItemClick:nil type:ZCChatCellClickTypeOpenURL obj:morelink];
        //
        //        }
    }
    return YES;
    
}

-(ZCTTMLEmojiLabel *)createLinkLabel:(CGFloat) y{
    ZCTTMLEmojiLabel *label = [[ZCTTMLEmojiLabel alloc] initWithFrame:CGRectMake(20, y, ScreenWidth - 40, 30)];
    [label setTextAlignment:NSTextAlignmentLeft];
    [label setFont:ListTimeFont];
    [label setTextColor:UIColorFromRGB(TextWhiteColor)];
    [label setLinkColor:UIColorFromRGB(TextLinkColor)];
    [label setDelegate:self];
    label.userInteractionEnabled = YES;
    
    return label;
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text{
    text = [ZZCoreTools replaceMessageEmoji:text];
    NSString *sugguestText = text;
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    if(sugguestDict){
        label.text = sugguestDict[@"text"];
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }
}

// 链接点击
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    DLog(@"链接地址:%@",url);
    if([@"resend" isEqual:url.absoluteString]){
        // 重新发送
        [self imgCodeShow];
    }
    
}

// 链接点击
-(void)ZCMLEmojiLabel:(ZCTTMLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(ZCTTMLEmojiLabelLinkType)type{
    DLog(@"意外添加的：%@",link);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
